package ast.nodes;

import scanner.Token;
import ast.ASTNode;
import ast.Evaluation;

/**
 * A series node has as its first child a RegEx, then the rest of the children will be
 * CommandNodes (Print, Replace, Insert,...etc)
 *
 *
 */
public class SeriesNode extends ASTNode {

    public SeriesNode()
    {
        super();
    }
    
    public SeriesNode(Token data)
    {
        super(data);
    }

    @Override
    public String toString(int depth) {
        String childrenStr = "";
        for (ASTNode child : getChildren()) {
            childrenStr += child.toString(depth+1);
        }
        return indent(depth) + "Series:" + childrenStr;
    }

    @Override
    public void run(Evaluation input) throws Exception {
        //find our regex node
    	RegExNode ren = null;
    	for(ASTNode child : children)
        	if(child instanceof RegExNode)
        		ren = (RegExNode)child;
    	
    	//if we have a match run any and all command nodes
    	if(ren!=null)
    	{
    		String re = "";
    		if(ren.getData() != null)
    			re = ren.getData().getTokenString() + "\n";
    		input.addNFA(re + ren.getNFA());
    		input.addDFA(re + ren.getDFA());
    	}
    	
		if(ren == null || ren.match(input.getCurrentLine()))
    		for(ASTNode child : children)
    			if(child instanceof CommandNode)
    				child.run(input);
    	
        //run our next series
    	for(ASTNode child : children)
        	if(child instanceof SeriesNode)
        	{
        		child.run(input);
        	}
    }

}
